package com.bum.api.processor.home.html.bum.bo;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.math.RandomUtils;

import com.bum.api.bo.RssBO;
import com.bum.api.core.exp.om.Metas;
import com.bum.api.core.exp.om.Params;
import com.bum.api.core.html.HtmlModel;
import com.bum.api.core.html.HtmlRender;
import com.bum.api.processor.rss.html.bo.RssHtmlViewBO;
import com.bum.api.processor.rss.html.bo.RssUrlHelper;
import com.bum.rss.exp.om.Rss;
import com.bum.rss.exp.om.RssEntry;

public class BumHomeHtmlBO {
	HtmlRender				htmlRender;
	RssBO					rssBO;

	private List<RssEntry>	rssSites	= null;
	private List<RssEntry>	rssEntries	= null;
	private long			nextMs		= 0;

	public String view(String path, Params params, Metas metas) {
		HtmlModel model = HtmlModel.get(metas);

		if (System.currentTimeMillis() > nextMs) {
			Rss rss = rssBO.load(null, null);
			if (rss != null) {
				rssSites = rss.getEntries();

				RssEntry topSite = rssSites.get(RandomUtils.nextInt(rssSites.size()));

				rss = rssBO.load(topSite.getUrl(), null);
				if (rss != null) {
					rssEntries = rss.getEntries();
				}

				nextMs = System.currentTimeMillis() + 300000L;
			}

		}

		model.put("rssSites", rssSites);
		if (CollectionUtils.isNotEmpty(rssEntries)) {
			RssHtmlViewBO.convertLinks(model, rssEntries, "rssEntries");
		}

		model.put("urlHelper", RssUrlHelper.get());

		return htmlRender.render("home/bum/bum-home", model);
	}

	public void setHtmlRender(HtmlRender htmlRender) {
		this.htmlRender = htmlRender;
	}

	public void setRssBO(RssBO rssBO) {
		this.rssBO = rssBO;
	}
}
